package com.hlkj.baojin.dao.repository;

import com.hlkj.baojin.constant.BaseRepository;
import com.hlkj.baojin.constant.BaojinConstant;
import com.hlkj.baojin.entity.AlarmRecord;
import com.hlkj.baojin.entity.EarlyAlarmRecord;
import com.hlkj.baojin.entity.dto.AlarmSearch;
import com.hlkj.baojin.entity.dto.ModelList;
import com.hlkj.baojin.utils.ErrororUtil;
import com.hlkj.baojin.utils.bean.Page;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AlarmRecordRepository extends BaseRepository<AlarmRecord> {
    int FIVE_MINUTES = 5 * 60 * 1000;

    @Value("${real.earlyWaveTime}")
    private Long earlyWaveTime;
//  #报警波动忽略时间
    @Value("${real.alarmWaveTime}")
    private Long alarmWaveTime;

    public AlarmRecordRepository(MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }

    /**
     * @param companyId 权限参数
     * @param alarmSearch 时间
     * @param companyIds 模糊查询对应id
     * @param deviceIds 模糊查询对应id
     * @param page
     * @return
     */
    public ModelList<AlarmRecord> listAlarmRecord(String companyId, AlarmSearch alarmSearch, List<String> companyIds, List<String> deviceIds, Page page) {
        Query query = new Query();

        query.addCriteria(Criteria.where("delete").is(BaojinConstant.IS_NO_DELETE));

        if (companyId != null) {
            query.addCriteria(Criteria.where("companyId").is(companyId));
        }

        query.addCriteria(new Criteria().orOperator(
                Criteria.where("companyId").in(companyIds),
                Criteria.where("deviceId").in(deviceIds)
        ));

        if (alarmSearch.getTimeEnd() != null && alarmSearch.getTimeStart() != null) {
            query.addCriteria(Criteria.where("createTime").gte(alarmSearch.getTimeStart()).lte(alarmSearch.getTimeEnd()));
        }

        query.with(new Sort(Sort.Direction.DESC, "createTime"));
        query.with(new Page(page.getPage(), page.getSize()));

        List<AlarmRecord> alarmRecordList = mongoTemplate.find(query, AlarmRecord.class);
        long count = mongoTemplate.count(query, AlarmRecord.class);

        ModelList<AlarmRecord> alarmRecordModelList = new ModelList<>(alarmRecordList, count);

        //TODO
        return alarmRecordModelList;
    }

    public boolean findByDevice(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("deviceId").is(id));
        long count = mongoTemplate.count(query, AlarmRecord.class);
        if (count==0) {
            return true;
        }else if(count>0){
            query.addCriteria(new Criteria().orOperator(Criteria.where("recoverStatus").is(null),Criteria.where("recoverStatus").is(1).and("recoverTime").gte(System.currentTimeMillis()-earlyWaveTime)));
            count = mongoTemplate.count(query, AlarmRecord.class);
            if(count==0){
                return true;
            }
        }
        return false;
    }

    public void recoverAlarm(String id, Long createTime) {
        Query query = Query.query(Criteria.where("deviceId").is(id).and("recoverStatus").is(null).and("delete").is(BaojinConstant.IS_NO_DELETE));
        Update update = Update.update("recoverStatus", 1);
        update.set("recoverTime",createTime);
        mongoTemplate.updateMulti(query, update, AlarmRecord.class);
    }

    /**
     * type 0:公司id删除 1.设备id删除
     * @param id
     * @param type
     */
    public void deleteAlarmRecord(String id, Integer type) {

        Query query = new Query();
        query.addCriteria(Criteria.where("delete").is(BaojinConstant.IS_NO_DELETE));
        if(type.equals(0)) {
            query.addCriteria(Criteria.where("companyId").is(id));
        } else if(type.equals(1)){
            query.addCriteria(Criteria.where("deviceId").is(id));
        } else {
            ErrororUtil.isError("报警记录", "数据异常");
        }

        Update update = new Update();
        update.set("delete", BaojinConstant.IS_DELETE);

        mongoTemplate.updateMulti(query, update, AlarmRecord.class);

    }

    public boolean findByDeviceEarly(String id) {
        Query query = new Query();
        boolean reulet=false;
        query.addCriteria(Criteria.where("deviceId").is(id));
        long count = mongoTemplate.count(query, EarlyAlarmRecord.class);
        if (count==0) {
            return true;
        }else if(count>0){
            query.addCriteria(new Criteria().orOperator(Criteria.where("recoverStatus").is(null),Criteria.where("recoverStatus").is(1).and("recoverTime").gte(System.currentTimeMillis()-alarmWaveTime)));
            count = mongoTemplate.count(query, EarlyAlarmRecord.class);
            if(count==0){
                return true;
            }

        }
        return false;
    }

    public void recoverEarlyAlarm(String id, long createTime) {
        Query query = Query.query(Criteria.where("deviceId").is(id).and("recoverStatus").is(null).and("delete").is(BaojinConstant.IS_NO_DELETE));
        Update update = Update.update("recoverStatus", 1);
        update.set("recoverTime",createTime);
        mongoTemplate.updateMulti(query, update, EarlyAlarmRecord.class);
    }

    public List<AlarmRecord> getNeedToSendSmsAlarms() {
        Query query = new Query();
        query.addCriteria(Criteria.where("recoverStatus").is(null)
                .and("delete").is(BaojinConstant.IS_NO_DELETE)
                .and("alarmStatus").is(0)
                .and("handleStatus").is(0)
                .and("smsTimes").lt(3)
                .and("updateTime").lte(System.currentTimeMillis() - FIVE_MINUTES));
        return mongoTemplate.find(query, AlarmRecord.class);
    }

    public void updateSmsAlarms(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        Update update = Update.update("updateTime", System.currentTimeMillis())
                .inc("smsTimes", 1);
        mongoTemplate.updateMulti(query, update, AlarmRecord.class);
    }
}
